/**
 * Copyright 2008-2009. Chongqing Communications Industry Services Co.,Ltd Information Technology Branch. All rights
 * reserved. <a>http://www.cqcis.com</a>
 */
package com.firebird.base.orm;

import java.lang.reflect.Field;
import java.util.Date;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang.StringUtils;

/**
 * @author qiuxj
 * @date 2009-11-14
 */
public class HibernateQueryUtil {
	
	  public static final String TYPE_LONG = "java.lang.Long";
	  public static final String TYPE_INTEGER = "java.lang.Integer";
	  public static final String TYPE_DATE = "java.util.Date";

	  public static String getTypeOfField(Class clazz, String fieldName)
	  {
	    Field field = null;
	    try {
	      if (fieldName.indexOf(46) == -1) {
	        field = clazz.getDeclaredField(fieldName);
	        return ((field != null) ? field.getType().getName() : "");
	      }
	      field = clazz.getDeclaredField(StringUtils.substringBefore(fieldName, "."));
	      return getTypeOfField(field.getType(), StringUtils.substringAfter(fieldName, "."));
	    }
	    catch (SecurityException e) {
	      e.printStackTrace();
	    } catch (NoSuchFieldException e) {
	      e.printStackTrace();
	    }
	    return null;
	  }

	  public static Map changeStringToClassFieldTypeOfMap(Class clazz, Map map) {
	    Set keys = map.keySet();
	    for (Object key : keys) {
	      Object value = map.get(key);
	      if (value instanceof String) {
	        String str = (String)map.get(key);
	        if ("java.lang.Long".equals(getTypeOfField(clazz, (String)key)))
	          map.put(key, Long.valueOf(str));
	        else if ("java.lang.Integer".equals(getTypeOfField(clazz, (String)key))) {
	          map.put(key, Integer.valueOf(str));
	        }
	      }
	    }
	    return map;
	  }

	  public static Map changeStringToClassFieldTypeOfMap(Class clazz, Map map, Boolean forceClear) {
	    Set keys = map.keySet();
	    for (Object key : keys) {
	      String srcKey = (String)key;
	      if (forceClear.booleanValue()) {
	        srcKey = srcKey.replaceAll("\\>|\\<|\\=|\\!|\\ |\\t", "");
	      }
	      Object value = map.get(key);
	      if (value instanceof String) {
	        String str = (String)map.get(key);
	        if ("java.lang.Long".equals(getTypeOfField(clazz, srcKey))) {
	          str = str.trim();
	          map.put(key, Long.valueOf(str));
	        } else if ("java.lang.Integer".equals(getTypeOfField(clazz, srcKey))) {
	          str = str.trim();
	          map.put(key, Integer.valueOf(str));
	        } else if ("java.util.Date".equals(getTypeOfField(clazz, srcKey))) {
	          str = str.trim();
	          map.put(key, new Date(Long.valueOf(str).longValue()));
	        }
	      }
	    }
	    return map;
	  }

}
